package demo03_DRUID连接池;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import demo01_JDBC入门.User;
import utils.JBDCUtils;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class Test_通过配置文件方式 {
    public static void main(String[] args)throws Exception {
        //创建properties对象
        Properties pro=new Properties();
        // - 加载配置文件中的数据
        FileInputStream fis = new FileInputStream("day_20\\src\\druid.properties"); pro.load(fis);
        //创建Druid连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);

        //获得连接
        Connection connection = dataSource.getConnection();
        //预编译sql语句,得到预编译对象
        String sql="select * from user where id=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        //设置sql语句参数
        ps.setInt(1,2);
        //执行sql语句,处理结果
        ResultSet resultSet = ps.executeQuery();
        //定义一个变量
        User user=null;
        while (resultSet.next()){
            //取值
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            String nickname = resultSet.getString("nickname");
            //封装
            user=new User(id,username,password,nickname);
        }
        //释放资源
        JBDCUtils.release(resultSet,ps,connection);
        System.out.println(user);

    }
}

